package com.nanxhs.concurrent.thread.pause;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * 使用join挂起线程示例
 *
 * @author: haibin.tang
 * @date: 2021/1/29
 */
public class JoinSample {

    private static final Queue<Integer> SEQUENCE_QUEUE = new LinkedBlockingDeque<>();

    private Thread printCodeThread;

    private void initSequence() {
        for (int index = 10000; index < 10010; ++index) {
            SEQUENCE_QUEUE.add(index);
        }
    }

    private void printCodeThread() {
        printCodeThread = new Thread(() -> {
            while (SEQUENCE_QUEUE.size() > 1) {
                System.out.println("消费code -->>> " + SEQUENCE_QUEUE.poll());
                LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
            }
        });
    }

    public static void main(String[] args) throws InterruptedException {
        JoinSample joinSample = new JoinSample();
        joinSample.initSequence();
        joinSample.printCodeThread();
        joinSample.printCodeThread.start();
        joinSample.printCodeThread.join();
        System.out.println("等待打印序号线程结束");
    }
}
